﻿using System;
using System.Collections.Generic;
using UnityEngine;

namespace YummyGame.Framework
{
    public enum SkillExecuterState
    {
        Free,
        Executing
    }
    public class SkillExecuter:IPoolObject,IDisposable
    {
        public SkillPrototype Prototype;
        public SkillOwner Owner;
        private SkillExecuterState m_state;
        public Skill Runtime;
        public TaskLooper taskLooper
        {
            get
            {
                return Owner.go.GetOrAddComponent<TaskLooper>();
            }
        }
        public SkillBaseInfo BaseInfo
        {
            get
            {
                return Prototype!=null ? Prototype.BaseInfo : null;
            }
        }
        public Dictionary<string, SkillAction> actions;
        private bool isFirst = true;
        private bool _isRunning = false;
        private bool _isDestroy = false;

        public SkillExecuter()
        {
            actions = new Dictionary<string, SkillAction>();
        }

        public bool Tick()
        {
            return _RunRoot(SkillKeyword.root_onstart)!=ActionRunState.Running;
        }

        private ActionRunState _RunRoot(string key)
        {
            if (!actions.ContainsKey(key)) return ActionRunState.Success;
            if (isFirst)
            {
                isFirst = false;
                return actions[key].Excute();
            }
            else
                return actions[key].Run();
        }

        public void OnEnable()
        {
            Prototype = null;
            Owner = null;
            Runtime = null;
            actions.Clear();
            isFirst = true;
        }

        public void OnDisable()
        {
            OnEnable();
        }

        public void Dispose()
        {
            if (_isDestroy) return;
            if (_isRunning) { }
            foreach (var action in actions.Values)
            {
                action.Dispose();
            }
            actions.Clear();
            
            _isDestroy = true;
            SingletonPool<SkillExecuter>.Instance.Recover(this);
        }
    }
}
